<?php
    $dbms='mysql';     //数据库类型
    $host='localhost'; //数据库主机名
    $dbName='xxx';    //数据库名
    $user='xxx';      //数据库用户名
    $pass='xxx';          //数据库密码
    $dsn="$dbms:host=$host;dbname=$dbName";
    try {
        $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
        //echo "连接成功<br/>";

		include_once "WXBizMsgCrypt.php";
		// 第三方发送消息给公众平台
		$encodingAesKey = "xxxxx";//与自建应用的接收消息服务器配置内的EncodingAESKey一致
		$token = "xxxxxx";//与自建应用的接收消息服务器配置内的token一致
		$corpId = "xxxxxxx";//企业微信corpId，企业微信后台->我的企业->企业ID
		//公众号服务器数据
		$sReqMsgSig = $sVerifyMsgSig = $_GET['msg_signature'];
		$sReqTimeStamp = $sVerifyTimeStamp = $_GET['timestamp'];
		$sReqNonce = $sVerifyNonce = $_GET['nonce'];
		$sReqData = file_get_contents("php://input");;
		$sVerifyEchoStr = $_GET['echostr'];
		$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId);
		if ($sVerifyEchoStr) {
			$sEchoStr = "";
			$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
			if ($errCode == 0) {
				print($sEchoStr);
			} else {
				print($errCode . "\n\n");
			}
			exit;
		}
		 //decrypt
		$sMsg = "";  //解析之后的明文
		$errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
		if ($errCode == 0) {
			$xml = new DOMDocument();
			$xml->loadXML($sMsg);
			$reqToUserName = $xml->getElementsByTagName('ToUserName')->item(0)->nodeValue;
			$reqFromUserName = $xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;
			$reqCreateTime = $xml->getElementsByTagName('CreateTime')->item(0)->nodeValue;
			$reqMsgType = $xml->getElementsByTagName('MsgType')->item(0)->nodeValue;
			$reqContent = $xml->getElementsByTagName('Content')->item(0)->nodeValue;
			$reqMsgId = $xml->getElementsByTagName('MsgId')->item(0)->nodeValue;
			$reqAgentID = $xml->getElementsByTagName('AgentID')->item(0)->nodeValue;

			//$mycontent=$reqContent;
			
			//判断输入是否为4为数字，真则查询电话。假则查询
			$contacts = "为您查询到以下人员：";
			if($reqContent == "帮助"){
				$mycontent="欢迎使用通讯录助手：<br>回复 电话号码 或 姓名、部门名称<br>即可查询相关信息<br>例如：“8408” 或 “张”<br>支持拼音查询";
			}else{
				foreach ($dbh->query('SELECT * from contacts WHERE `partment` LIKE "%'.$reqContent.'%" or `py_partment` LIKE "%'.$reqContent.'%" or `name` LIKE "%'.$reqContent.'%" or `py_name` LIKE "%'.$reqContent.'%" or `telephone` LIKE "%'.$reqContent.'%" or `mobile` LIKE "%'.$reqContent.'%"') as $row) {
					$contacts = $contacts . '<br>' . $row["partment"] . ' / ' . $row["name"] . ' / ' . $row["telephone"];
				}
				if(!empty($row['name'])){
					$mycontent=$contacts;
				}else{
					$mycontent="抱歉，暂无查询结果<br>使用说明请回复 “帮助”<br>如需登记，请联系数据中心<br>电话：6108408";
				}
			}
			
			//消息格式
			$sRespData =
				"<xml>
				<ToUserName><![CDATA[".$reqFromUserName."]]></ToUserName>
				<FromUserName><![CDATA[".$corpId."]]></FromUserName>
				<CreateTime>".sReqTimeStamp."</CreateTime>
				<MsgType><![CDATA[text]]></MsgType>
				<Content><![CDATA[".$mycontent."]]></Content>
				</xml>";
			$sEncryptMsg = ""; //xml格式的密文
			$errCode = $wxcpt->EncryptMsg($sRespData, $sReqTimeStamp, $sReqNonce, $sEncryptMsg);
			if ($errCode == 0) {
				//file_put_contents('smg_response.txt', $sEncryptMsg); //debug:查看smg
				print($sEncryptMsg);
			} else {
				print($errCode . "\n\n");
			}
		} else {
			print($errCode . "\n\n");
		}

        $dbh = null;
    } catch (PDOException $e) {
        die ("Error!: " . $e->getMessage() . "<br/>");
    }
    //默认这个不是长连接，如果需要数据库长连接，需要最后加一个参数：array(PDO::ATTR_PERSISTENT => true) 变成这样：
    $db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));

?>